/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Persistence;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import servidorped.User;

/**
 *
 * @author Micosil
 */
public class UserDatabase implements UserPersistence {

    //Parte de este código está tomado de otras partes, especialmente internet.
    String url = null;
    String dbName = null;
    String driver = null;
    String userName = null;
    String password = null;

    public UserDatabase(String pathToConfigFile) {
        BufferedReader configReader = null;
        try {
            configReader = new BufferedReader(new FileReader(new File(pathToConfigFile)));
            configReader.readLine();
            url = configReader.readLine();
            dbName = configReader.readLine();
            driver = configReader.readLine();
            userName = configReader.readLine();
            password = configReader.readLine();

            //Connection test.
            Connection conn = openConnection();
            closeConnection(conn);

        } catch (IOException ex) {
            Logger.getGlobal().log(Level.SEVERE, "Could not load Database Parameters.");
        } finally {

            if (configReader != null) {
                try {
                    configReader.close();
                } catch (IOException ex) {
                    Logger.getGlobal().log(Level.SEVERE, null, ex);
                }
            }

        }

    }

    private Connection openConnection() {
        Connection conn = null;
        try {
            Class.forName(driver).newInstance();

            conn = DriverManager.getConnection(url + dbName, userName, password);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            Logger.getGlobal().log(Level.SEVERE, "Encountered the following exception when creating a connection: ", ex);
        }
        return conn;
    }

    private void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
            }
        }
    }

    private void closeResultSet(ResultSet res) {
        if (res != null) {
            try {
                res.close();
            } catch (SQLException ex) {
            }
        }
    }

    private void closePreparedStatement(PreparedStatement prep) {
        if (prep != null) {
            try {
                prep.close();
            } catch (SQLException ex) {
            }
        }
    }

    @Override
    public List<User> retrieveUsers() {
        Connection conn = openConnection();
        List<User> response = new ArrayList();
        PreparedStatement statement = null;
        ResultSet result = null;
        try {
            statement = conn.prepareStatement("SELECT * FROM CHATMICOSIL.USUARIO;");
            result = statement.executeQuery();
            while (result.next()) {

                response.add(new User(result.getString("Producto_userName"),
                        result.getString("Producto_realName"),
                        result.getString("Producto_password"),
                        result.getString("Producto_email"),
                        result.getBoolean("Producto_isAdmin")));
            }

        } catch (SQLException ex) {
            Logger.getGlobal().log(Level.SEVERE, null, ex);
        } finally {
            closeConnection(conn);
            closePreparedStatement(statement);
            closeResultSet(result);
        }
        return response;
    }

    @Override
    public User getUserByName(String nameToBeFound) {
        Connection conn = openConnection();
        User response = null;
        PreparedStatement statement = null;
        ResultSet result = null;
        try {
            statement = conn.prepareStatement("SELECT * FROM CHATMICOSIL.USUARIO WHERE USUARIO_USERNAME = ?");
            statement.setString(1, nameToBeFound);
            result = statement.executeQuery();
            result.next();
            response = new User(result.getString("USUARIO_USERNAME"),
            result.getString("USUARIO_REALNAME"),
            result.getString("USUARIO_PASSWORD"),
            result.getString("USUARIO_EMAIL"),
            result.getBoolean("USUARIO_ISADMIN"));

        } catch (SQLException ex) {
            Logger.getGlobal().log(Level.SEVERE, null, ex);
        } finally {
            closeConnection(conn);
            closePreparedStatement(statement);
            closeResultSet(result);
        }
        return response;
    }

    @Override
    public boolean createUser(User user) {
        Connection conn = openConnection();
        Boolean response = null;
        PreparedStatement statement = null;
        try {
            statement = conn.prepareStatement("INSERT INTO CHATMICOSIL.USUARIO (USUARIO_USERNAME, USUARIO_REALNAME,"
                    + "USUARIO_PASSWORD, USUARIO_EMAIL, USUARIO_ISADMIN) "
                    + "VALUES (?, ?, ?, ?, ?)");

            statement.setString(1, user.getUserName());
            statement.setString(2, user.getRealName());
            statement.setString(3, user.getPassword());
            statement.setString(4, user.getEmailAdress());
            statement.setBoolean(5, false);

            response = statement.execute();


        } catch (SQLException ex) {
            Logger.getGlobal().log(Level.SEVERE, null, ex);
            response = false;
        } finally {
            closeConnection(conn);
            closePreparedStatement(statement);
        }
        return response;


    }

    @Override
    public boolean deleteUser(String userName) {
        Connection conn = openConnection();
        PreparedStatement statement = null;
        boolean result = false;
        try {
            statement = conn.prepareStatement("DELETE FROM CHATMICOSIL.USUARIO_CONVERSATION WHERE USUARIO_USERNAME = ?");
            statement.setString(1, userName);      
            statement.execute();
            statement = conn.prepareStatement("DELETE FROM CHATMICOSIL.USUARIO WHERE USUARIO_USERNAME = ?");
            result = true;          
        } catch (SQLException ex) {
            ex.printStackTrace();
            Logger.getGlobal().log(Level.SEVERE, null, ex);         
        } finally {
            closeConnection(conn);
            closePreparedStatement(statement);
            return result;
        }        
    }
}
